//
//  CoreGraphicsTestViewController.m
//  CoreGraphicsTest
//
//  Created by aewatson on 11/7/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CoreGraphicsTestViewController.h"


@implementation CoreGraphicsTestViewController

@synthesize controlView;
@synthesize graphicsView;
@synthesize myTimer;
@synthesize gameModel;
@synthesize spriteViews;
@synthesize lastTick;
@synthesize blueButton;
@synthesize redButton;
@synthesize yellowButton;
@synthesize greenButton;
@synthesize blockImages;
@synthesize roundLabel;
@synthesize scoreLabel;
@synthesize readyButton;
@synthesize pauseButton;
@synthesize backButton;
@synthesize statusLabel;
@synthesize summaryLabel;
@synthesize soundPlayer;

- (NSTimer*)createTimer {
    // create timer on run loop
    return [NSTimer scheduledTimerWithTimeInterval:REFRESH_INTERVAL target:self selector:@selector(timerTicked:) userInfo:nil repeats:YES];
    lastTick = [NSDate date];
}

// Captures timer tick 
- (void)timerTicked:(NSTimer*)timer {
    [gameModel timerTickedAfterMilliseconds:REFRESH_INTERVAL*1000];
    //Do stuff
    [self updateView];
}

- (void) updateView {
    for (id spriteView in spriteViews) {
        // do something with object
        [spriteView updateFromModel];
    }
}

// To be called when game is over to stop timer
- (void)actionStop:(id)sender {
    // stop the timer
    [myTimer invalidate];
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)createViewWithModel:(SpriteModel*) spriteModel {
    SpriteView *spriteView = [[SpriteView alloc] initWithSpriteModel:spriteModel andImages:blockImages];
    [spriteViews addObject:spriteView];
    [[self graphicsView] addSubview:spriteView];
}

- (void)removeViewWithModel:(SpriteModel*) spriteModel {
    SpriteView *spriteViewToRemove;
    for(SpriteView *spriteView in spriteViews) {
        if(spriteView.spriteModel == spriteModel) {
            spriteViewToRemove = spriteView;
        }
    }
    [spriteViewToRemove removeFromSuperview];
    [spriteViews removeObject:spriteViewToRemove];
    [spriteViewToRemove release];
}

- (void)changeViewStateWithModel:(SpriteModel*) spriteModel {
    SpriteView *spriteViewToChange;
    for(SpriteView *spriteView in spriteViews) {
        if(spriteView.spriteModel == spriteModel) {
            spriteViewToChange = spriteView;
        }
    }
    [spriteViewToChange nextState];
}

/*
- (void)spriteAdded:(NSNotification *)notification {
	id notificationSender = [notification object];
    NSLog(@"Sprite created!");
	//do stuff
    // create view representation of block
    [self createViewWithModel:notificationSender];
}
*/

- (void)blockAdded:(NSNotification *)notification {
	id notificationSender = [notification object];
    NSLog(@"Block created!");
	//do stuff
    // create view representation of block
    [self createViewWithModel:notificationSender];
    // play sound
    [[self soundPlayer] playBlock];
}

- (void)shotAdded:(NSNotification *)notification {
	id notificationSender = [notification object];
    NSLog(@"Shot created!");
	//do stuff
    // create view representation of block
    [self createViewWithModel:notificationSender];
    // play sound
    [[self soundPlayer] playShot];
}

- (void)explosionAdded:(NSNotification *)notification {
	id notificationSender = [notification object];
    NSLog(@"Explosion created!");
	//do stuff
    // create view representation of block
    [self createViewWithModel:notificationSender];
    // play sound
    [[self soundPlayer] playExplosion];
}

- (void)spriteRemoved:(NSNotification *)notification {
    id notificationSender = [notification object];
    NSLog(@"Sprite removed!");
	//do stuff
    // create view representation of block
    [self removeViewWithModel:notificationSender];
}

- (void)spriteStateChanged:(NSNotification *)notification {
    id notificationSender = [notification object];
    NSLog(@"Sprite state changed!");
	//do stuff
    // create view representation of block
    [self changeViewStateWithModel:notificationSender];
}

- (void)roundEnded:(NSNotification *)notification {
    NSLog(@"Round ended!");
    [self actionStop:self];
    // play sound
    [[self soundPlayer] playRoundEnd];
    [summaryLabel setText:[gameModel getSummary]];
    [statusLabel setText:[gameModel getStatus]];
    [pauseView setHidden:false];
    [pauseButton setEnabled:false];
}

- (void)scoreChanged:(NSNotification *)notification {
    NSLog(@"Score changed!");
    [scoreLabel setText:[gameModel getScoreString]];
}

- (IBAction)redButtonPressed {
    NSLog(@"Red button pressed!");
    [gameModel addShotWithColor:RED];
}

- (IBAction)greenButtonPressed {
    NSLog(@"Green button pressed!");
    [gameModel addShotWithColor:GREEN];
}

- (IBAction)blueButtonPressed {
    NSLog(@"Blue button pressed!");
    [gameModel addShotWithColor:BLUE];
}

- (IBAction)yellowButtonPressed {
    NSLog(@"Yellow button pressed!");
    [gameModel addShotWithColor:YELLOW];
}

- (IBAction)readyButtonPressed {
    NSLog(@"Ready button pressed!");
    // hide pause window
    [pauseView setHidden:true];
    [pauseButton setEnabled:true];
    [summaryLabel setText:@""];
    [roundLabel setText:[gameModel getRoundString]];
    // start timer
    [self startTimer];
}

- (IBAction)pauseButtonPressed {
    NSLog(@"Pause button pressed!");
    // stop timer
    [self actionStop:self];
    // show pause window
    [pauseView setHidden:false];
    [pauseButton setEnabled:false];
    }

- (IBAction)backButtonPressed {
    NSLog(@"Back button pressed!");
    
}

- (void)startTimer {
    // records time since last timer tick
    lastTick = [[NSDate alloc] init];
    myTimer = [self createTimer];
}


#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    //[self setSoundPlayer:[[[SoundPlayer alloc] init] autorelease]];
    
    // load sounds
    [self setSoundPlayer:[[[SoundPlayer alloc] init] autorelease]];
   
    // my code
    [self setGameModel:[[[GameModel alloc] init] autorelease]];
    
    // add event listeners
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(blockAdded:) name:@"blockAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shotAdded:) name:@"shotAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(explosionAdded:) name:@"explosionAdded" object:nil];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(spriteAdded:) name:@"spriteAdded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(spriteRemoved:) name:@"spriteRemoved" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(spriteStateChanged:) name:@"spriteStateChanged" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(roundEnded:) name:@"roundEnded" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scoreChanged:) name:@"scoreChanged" object:nil];
    
    // initialize view data members
    spriteViews = [[NSMutableArray alloc] initWithCapacity:20];
        
    NSMutableArray *yellowAnim = [[[NSMutableArray alloc] initWithCapacity:15] retain];
    NSMutableArray *greenAnim = [[[NSMutableArray alloc] initWithCapacity:15] retain];
    NSMutableArray *blueAnim = [[[NSMutableArray alloc] initWithCapacity:15] retain]; 
    NSMutableArray *redAnim = [[[NSMutableArray alloc] initWithCapacity:15] retain];  
    NSMutableArray *bulletImages = [[[NSMutableArray alloc] initWithCapacity:4] retain];
    
    // get images from resource files
    NSString *fileName;
    NSString *bundlePath;
    UIImage *image;
    
    // get block images with their explosion animations
    for (int i = 0; i < 15; i++) {
        fileName = [NSString stringWithFormat:@"yellow%04d", i + 1];
        bundlePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"png"];
        image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
        [yellowAnim addObject:image];
    }
    
    for (int i = 0; i < 15; i++) {
        fileName = [NSString stringWithFormat:@"red%04d", i + 1];
        bundlePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"png"];
        image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
        [redAnim addObject:image];
    }
    
    for (int i = 0; i < 15; i++) {
        fileName = [NSString stringWithFormat:@"blue%04d", i + 1];
        bundlePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"png"];
        image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
        [blueAnim addObject:image];
    }
    
    for (int i = 0; i < 15; i++) {
        fileName = [NSString stringWithFormat:@"green%04d", i + 1];
        bundlePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"png"];
        image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
        [greenAnim addObject:image];
    }
    
    // get bullet images
    bundlePath = [[NSBundle mainBundle] pathForResource:@"yellow_bullet" ofType:@"png"];
    image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
    [bulletImages addObject:image];
    
    bundlePath = [[NSBundle mainBundle] pathForResource:@"red_bullet" ofType:@"png"];
    image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
    [bulletImages addObject:image];
    
    bundlePath = [[NSBundle mainBundle] pathForResource:@"blue_bullet" ofType:@"png"];
    image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
    [bulletImages addObject:image];
    
    bundlePath = [[NSBundle mainBundle] pathForResource:@"green_bullet" ofType:@"png"];
    image = [[[UIImage alloc] initWithContentsOfFile:bundlePath] autorelease];
    [bulletImages addObject:image];

    // add to images class
    blockImages = [[BlockImages alloc] initWithRedAnim:redAnim blueAnim:blueAnim greenAnim:greenAnim yellowAnim:yellowAnim andBullets: bulletImages];
    
    // set text elements
    [summaryLabel setTextAlignment:UITextAlignmentCenter];
    [summaryLabel setText:@""];
    [statusLabel setTextAlignment:UITextAlignmentCenter];
    [statusLabel setText:[gameModel getStatus]];
    [scoreLabel setTextAlignment:UITextAlignmentRight];
    [scoreLabel setText:[gameModel getScoreString]];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
